import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/components/image_network.dart';
import 'package:mall/components/product_price.dart';
import 'package:mall/core/models/address.dart';
import 'package:mall/core/models/cart_list.dart';
import 'package:mall/core/models/delivery_status.dart';
import 'package:mall/core/models/jump_type.dart';
import 'package:mall/core/models/order_checkout.dart';
import 'package:mall/core/models/order_confirm.dart';
import 'package:mall/core/models/order_status.dart';
import 'package:mall/core/models/product_detail.dart' as price;
import 'package:mall/core/services/api.dart';
import 'package:mall/screens/address/address_page.dart';
import 'package:mall/screens/group/group_history_screen.dart';
import 'package:mall/screens/main/main_page.dart';
import 'package:mall/screens/order/order_page.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'components/order_pay_sheet.dart';

class OrderConfirmScreenArgs {
  final Map<int, int> cartIdQuantity;
  final List<int> portIds;

  OrderConfirmScreenArgs(
    this.cartIdQuantity, {
    this.portIds,
  });
}

/// 订单确认页面
class OrderConfirmScreen extends StatefulWidget {
  static const routeName = "/OrderConfirmScreen";
  final OrderConfirmScreenArgs args;

  const OrderConfirmScreen({
    Key key,
    @required this.args,
  }) : super(key: key);

  @override
  _OrderConfirmScreenState createState() => _OrderConfirmScreenState();
}

class _OrderConfirmScreenState extends State<OrderConfirmScreen> {
  String _error;
  OrderConfirm _orderConfirm;
  OrderConfirmAddress _address;

  // 买家留言
  final _formKey = GlobalKey<FormState>();
  Map<int, String> _orderMemos = {};

  @override
  void initState() {
    super.initState();
    _fetchConfirmInfo();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("订单确认"),
      ),
      body: _error == null && _orderConfirm == null
          ? Center(
              child: CircularProgressIndicator(),
            )
          : _orderConfirm == null
              ? Center(
                  child: Text("$_error"),
                )
              : _buildBody(),
    );
  }

  Widget _buildBody() {
    return SafeArea(
      child: Form(
        key: _formKey,
        child: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                padding: EdgeInsets.symmetric(vertical: 8.w),
                child: Column(
                  children: [
                    _buildAddress(),
                    SizedBox(height: 8.w),
                    Wrap(
                      runSpacing: 8.w,
                      children: List.generate(
                        _orderConfirm.carts.length,
                        (index) => _buildStoreItem(_orderConfirm.carts[index]),
                      ),
                    ),
                    SizedBox(height: 8.w),
                    _buildTotal(),
                  ],
                ),
              ),
            ),
            Container(
              padding: EdgeInsets.only(right: 8.w),
              color: Colors.white,
              height: 50.w,
              child: Row(
                children: [
                  Spacer(),
                  RaisedButton(
                    onPressed: _onSubmitOrder,
                    elevation: 0,
                    child: Text("提交订单"),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  /// 地址信息
  Widget _buildAddress() {
    final address = _address ?? _orderConfirm.defaultAddress;
    if (address == null) {
      return GestureDetector(
        onTap: _onTapAddress,
        child: Container(
          padding: EdgeInsets.all(8.w),
          color: Colors.white,
          width: double.infinity,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text("点击选择地址"),
              Icon(Icons.arrow_forward_ios),
            ],
          ),
        ),
      );
    }

    return GestureDetector(
      onTap: _onTapAddress,
      child: Container(
        padding: EdgeInsets.all(8.w),
        color: Colors.white,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  "${address.linkMan}    ${address.contactPhone}",
                  style: TextStyle(fontSize: 16.sp),
                ),
                SizedBox(height: 11.w),
                Text("${address.fullAddress}"),
              ],
            ),
            Icon(Icons.arrow_forward_ios),
          ],
        ),
      ),
    );
  }

  /// 店铺信息
  Widget _buildStoreItem(Store store) {
    return Container(
      padding: EdgeInsets.all(8.w),
      color: Colors.white,
      width: 375.w,
      child: Column(
        children: [
          Row(
            children: [
              ImageNetwork(url: "null", width: 20.w, height: 20.w),
              SizedBox(width: 8.w),
              Text("${store.storeName}"),
              Spacer(),
              Text("共${store.cartList.length}件商品", style: TextStyle(fontSize: 12.sp)),
            ],
          ),
          SizedBox(height: 8.w),
          Wrap(
            runSpacing: 8.w,
            children: List.generate(
              store.cartList.length,
              (index) => _buildItem(store.cartList[index]),
            ),
          ),
          SizedBox(height: 8.w),
          Align(
            alignment: Alignment.centerLeft,
            child: Text(
              "订单说明：${_orderConfirm.orderDesc ?? "--"}",
              style: TextStyle(fontSize: 10.sp),
            ),
          ),
          Divider(),
          Row(
            children: [
              Text("买家留言", style: TextStyle(fontSize: 12.sp)),
              Expanded(
                child: TextFormField(
                  textAlign: TextAlign.end,
                  decoration: InputDecoration(
                    hintText: "给卖家留言",
                    focusedBorder: InputBorder.none,
                    enabledBorder: InputBorder.none,
                    border: InputBorder.none,
                  ),
                  onSaved: (value) => _orderMemos[store.storeId] = value,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 商品信息
  Widget _buildItem(Cart cart) {
    return Row(
      children: [
        ClipRRect(
          borderRadius: BorderRadius.circular(4.w),
          child: ImageNetwork(url: "${cart.productImage}", width: 70.w, height: 70.w),
        ),
        SizedBox(width: 8.w),
        Expanded(
          child: SizedBox(
            height: (70 - 8).w,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text("${cart.productName}"),
                ProductPrice(list: cart.priceVos),
              ],
            ),
          ),
        ),
        Text("x${cart.quantity}"),
      ],
    );
  }

  /// 总支付
  Widget _buildTotal() {
    return Column(
      children: [
        Container(
          padding: EdgeInsets.all(8.w),
          color: Colors.white,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text("配送方式"),
              Text("快递配送", style: TextStyle(fontSize: 12.sp)),
            ],
          ),
        ),
        SizedBox(height: 8.w),
        Wrap(
          runSpacing: 1.w,
          children: List.generate(
            _orderConfirm.totalPriceVos.length,
            (index) => _buildTotalItem(_orderConfirm.totalPriceVos[index]),
          ),
        ),
      ],
    );
  }

  /// 支付金额
  Widget _buildTotalItem(price.Price price) {
    return Container(
      padding: EdgeInsets.all(8.w),
      color: Colors.white,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text("${price.priceTypeName}"),
          Text(
            "${price.pointCoin}",
            style: TextStyle(color: Theme.of(context).primaryColor, fontWeight: FontWeight.bold),
          ),
        ],
      ),
    );
  }

  /// 获取确认信息
  void _fetchConfirmInfo() async {
    final api = context.read<Api>();
    try {
      final orderConfirm = await api.orderConfirmEx(
        widget.args.cartIdQuantity,
        widget.args.portIds,
      );
      if (!mounted) {
        return;
      }
      setState(() {
        _orderConfirm = orderConfirm;
      });
    } on DioError catch (e) {
      if (!mounted) {
        return;
      }
      setState(() {
        _error = e.message;
      });
    }
  }

  /// 点击地址
  void _onTapAddress() async {
    final result = await Navigator.of(context).push<Address>(
      MaterialPageRoute(builder: (context) => AddressPage(args: true)),
    );
    if (result == null) {
      return;
    }
    setState(() {
      _address = result.toOrderConfirmAddress();
    });
  }

  /// 提交订单
  void _onSubmitOrder() async {
    // 判断地址
    final addressId = _address?.id ?? _orderConfirm.defaultAddress?.id;
    if (addressId == null) {
      EasyLoading.showToast('请选择地址');
      return;
    }
    // 保存买家留言
    _formKey.currentState.save();
    // 支付页面
    final orderCheckout = await showModalBottomSheet<OrderCheckout>(
      context: context,
      isScrollControlled: true,
      builder: (context) => OrderPaySheet(
        portIds: widget.args.portIds,
        orderConfirm: _orderConfirm,
        addressId: addressId,
        storeCarts: widget.args.cartIdQuantity,
        orderMemos: _orderMemos,
      ),
    );
    // 转到订单页面 or 拼购历史页面
    if (orderCheckout?.jumpType == JumpType.JUMP_IN_ORDER_LIST) {
      // 判断订单状态
      var index = 0;
      if (orderCheckout?.orderStatus != OrderStatus.PAID) {
        index = 1;
      } else if (orderCheckout?.deliveryStatus == DeliveryStatus.PARTIALLY) {
        index = 2;
      } else if (orderCheckout?.deliveryStatus == DeliveryStatus.CONFIRMING) {
        index = 3;
      }
      // 导航到订单列表页面，并清空栈到首页
      Navigator.of(context).pushNamedAndRemoveUntil(
        OrderPage.routeName,
        ModalRoute.withName(MainPage.routeName),
        arguments: OrderPageArgs(null, index),
      );
    } else if (orderCheckout?.jumpType == JumpType.JUMP_IN_PIN_GOU_HISTORIES) {
      // 导航到拼购历史页面，并清空栈到首页
      Navigator.of(context).pushNamedAndRemoveUntil(
        GroupHistoryScreen.routeName,
        ModalRoute.withName(MainPage.routeName),
      );
    } else {
      Navigator.of(context).pop();
    }
  }
}
